from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from product.models import Product


def product(request):
    products = Product.objects.all()
    return render(request, 'product.html', {'products': products})


def product_manage(request):
    products = Product.objects.all()
    products_data = [
        {
            'id': product.id,
            'name': product.name,
            'classify': product.classify,
            'img': product.img,
            'detail': product.detail,
        } for product in products
    ]
    return JsonResponse({'products': products_data})


from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from .models import Product
import json


@require_http_methods(["POST"])
def update_product(request, product_id):
    try:
        data = json.loads(request.body)
        product = Product.objects.get(pk=product_id)
        product.name = data.get('name', product.name)
        product.classify = data.get('classify', product.classify)
        product.img = data.get('img', product.img)
        product.detail = data.get('detail', product.detail)
        product.save()
        return JsonResponse({'message': 'Product updated successfully'})
    except Product.DoesNotExist:
        return JsonResponse({'error': 'Product not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


@require_http_methods(["DELETE"])
def delete_product(request, product_id):
    try:
        product = Product.objects.get(pk=product_id)
        product.delete()
        return JsonResponse({'message': 'Product deleted successfully'})
    except Product.DoesNotExist:
        return JsonResponse({'error': 'Product not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


@csrf_exempt
def create_product(request):
    if request.method == "POST":
        data = json.loads(request.body)
        product = Product.objects.create(
            name=data['name'],
            classify=data['classify'],
            img=data['img'],
            detail=data['detail']
        )
        return JsonResponse({'message': 'Product created successfully', 'id': str(product.id)}, status=201)
    else:
        return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
